﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// 文本扩展
    /// </summary>
    public static class DBTextExtention
    {
        /// <summary>
        /// 得到文本的位置
        /// </summary>
        /// <param name="txt">文本实体</param>
        /// <returns>文本的位置点</returns>
        public static Point3d GetBasePosion(this DBText txt)
        {
            if (txt.HorizontalMode == TextHorizontalMode.TextLeft && txt.VerticalMode == TextVerticalMode.TextBase)
                return txt.Position;
            else
                return txt.AlignmentPoint;
        }

        /// <summary>
        /// 设置文本的位置
        /// </summary>
        /// <param name="txt">文本实体</param>
        /// <param name="pt">文本的位置点</param>
        public static void SetBasePosion(this DBText txt, Point3d pt)
        {
            if (txt.HorizontalMode == TextHorizontalMode.TextLeft && txt.VerticalMode == TextVerticalMode.TextBase)
            {
                txt.Position = pt;
            }
            else
            {
                txt.AlignmentPoint = pt;
            }
        }

        /// <summary>
        /// 设置文本的字体
        /// </summary>
        /// <param name="txt">文本实体</param>
        /// <param name="textStyleName">字体名字</param>
        /// <param name="onlyTextStyle">是否只是设置字体，不改变高度，角度，宽度比例(依据文本样式的设置)</param>
        public static void SetTextStyle(this DBText txt, string textStyleName, bool onlyTextStyle)
        {
            Database db = txt.Database;
            Transaction trans = db.TransactionManager.TopTransaction;
            TextStyleTable st = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForRead);

            if (st.Has(textStyleName))
            {
                txt.TextStyleId = st[textStyleName];
            }
            else
            {
                throw new System.Exception("不存在" + textStyleName);
            }

            if (!onlyTextStyle)
            {
                TextStyleTableRecord str = (TextStyleTableRecord)trans.GetObject(st[textStyleName], OpenMode.ForRead);
                if (str.ObliquingAngle != 0)
                    txt.Rotation = str.ObliquingAngle;
                if (str.TextSize != 0)
                    txt.Height = str.TextSize;
                if (str.XScale != 0)
                    txt.WidthFactor = str.XScale;
            }
        }

        /// <summary>
        /// 设置居中
        /// </summary>
        /// <param name="txt">文本实体</param>
        /// <param name="pt">位置</param>
        public static void SetCenteredMode(this DBText txt, Point3d pt)
        {
            txt.Position = pt;
            txt.VerticalMode = TextVerticalMode.TextBase;
            txt.HorizontalMode = TextHorizontalMode.TextMid;
            txt.AlignmentPoint = txt.Position;
        }
    }
}
